<?php

class ThreadsController extends Zend_Controller_Action
{

    public function init()
    {
        try{
    		$session = Zend_Registry::get('session');
    		
    		if($session->user['Username'] != ""){ //ako ne e prazna sesijata znaci deka korisnikot e logiran.
    			
    		}        
        	else{        		
    			$this->_helper->redirector('index','login'); //vo sprotivno vrati go na stranata za logiranje.
    		} 
        
        }
        catch (Zend_Exception $e) {  
			echo "Error message: " . $e->getMessage() . "\n";  
        
        }
    }

    public function indexAction()
    {
        $session = Zend_Registry::get('session');
        $userID = $session->user['id'];
        
        $threadOB = new Application_Model_DbTable_Threads();
        $myThreads = $threadOB->getUserThreads($userID);
        $this->view->myThreads = $myThreads;
        
        if ($this->getRequest()->isPost()) {
        	
        	if (isset($_POST['btn_DeleteThread'])){
		    		$id = $this->getRequest()->getParam("hdn_ThreadCurrentDelete");
		    		$threadOB->deleteThread($id);
		    		$this->_helper->redirector('index');
        	}
        }
    }

    public function createnewAction()
    {
    try{
    		
    	$form = new Application_Form_Newthread();
        $form->submit->setLabel('Post');	// postavuvanje na ime na kopceto za sabmitiranje.
        $this->view->form = $form;
        
        
        
    	if ($this->getRequest()->isPost()) {    // ako e kliknato na submit kopceto
			$formData = $this->getRequest()->getPost();
			
			if ($form->isValid($formData)) {     // se proveruva dali se popolneti site polinja.
				
				//zemi gi vrednostite vneseni vo polinjata.
				$title = $form->getValue('title');
				$text = $form->getValue('text');
				$tags = $form->getValue('tags');
				
				//kreiranje na objekti od model klasite.
				$thread_OB = new Application_Model_DbTable_Threads();
				$tag_OB = new Application_Model_DbTable_Tag();
				$tag_thread_OB = new Application_Model_DbTable_Searchterm();
				$user_OB = new Application_Model_DbTable_Users();
				
				
				//id na korisnikot koj e logiran momentalno.
				$session = Zend_Registry::get('session');
 				$userID = $session->user['id'];
				
 				$threadID = $thread_OB->createThread($title, $text, $userID); //se kreira stavka vo tabelata Threads.
 				
				//formatiranje na stringot od tags poelto.
				$lowered = strtolower($tags);				// site golemi bukvi napravi gi mali (lower case).
				$trimmed = str_replace(" ", "", $lowered);	// isfrli gi site prazni mesta od stringot koj e vnesen vo poleto tags.
				$pieces = explode(",", $trimmed);			// potoa podeli go stingot na povekje stringovi (delimiter -> zapirka).
				
				$allTags = $tag_OB->getAll();		// Zemi gi site tagovi koi vekje postojat (site od tabelata Tag).
								
				
				foreach ($pieces as $peace)			// Za site tagovi koi vekje postojat bo bazata.
				{
					$tagID = 0;
					$flag = 0;
					
					foreach ($allTags as $tag)		// Za site tagovi vneseni vo poleto pri kreiranje na Thread.
					{
						if(strcmp($tag['Term'], $peace) == 0 )		// Ako nekoj od tagovite koi se vneseni vekje gi ima vo bazata:
						{
							$tagID = $tag_OB->getID($peace);		// Togash zemi go ID-to na toj tag
							$flag = 1;								// Zabelezi deka eden tag vekje posti vo bazata
							break;									// Izlezi od vnatreshniot foreach
						}

					}	//End foreach (vnatreshen)
					
					if($flag == 0){									// Dokolku flgot ostanal 0 znaci takov tag ne posti vo bazata
						$newTagID = $tag_OB->createTag($peace);					// Kreiraj nova stavka vo tabelata vo bazata
						$tag_thread_OB->addSearchTerm($newTagID, $threadID);	// I kreiraj vrska pomegju toj tag i ovoj Thread.
					}
					elseif($flag == 1){								// Dokolku flagot e 1, vekje ima takov tag
						$tag_thread_OB->addSearchTerm($tagID, $threadID);	// Kreiraj vrska pomegju ovoj Thread i vekje postoechkiot tag.						
					}
				} //End foreach (nadvoreshen)
				
 				
				$this->_helper->redirector('index');
			} 
			else {							//ako ne se, togash se vrakja se vo sostojba koja bila pred kliknuvanje ka kopceto 
				$form->populate($formData);		//If the form data is not valid, then we populate the form with the data that the user filled in and redisplay.
			}
    	}
    }//End try.
    catch (Zend_Exception $e) {  
			echo "Error message: " . $e->getMessage() . "\n";  
        
        }

    }//End createnewAction  
    

    public function viewthreadAction()
    {
    	try{
    		$thread_BO = new Application_Model_DbTable_Threads();
    		$userOB = new Application_Model_DbTable_Users();
    		
    		if (is_numeric($this->_request->getQuery('id'))){
    			$id =$this->_request->getQuery('id');
    			$thread = $thread_BO->getThread($id);
    			$user = $userOB->getUser($thread['User_id']);
    			
    			if ($thread == NULL){
					$flag_show =0;	
					$this->view->flag_show = $flag_show;
    			}
    			else{
    				$flag_show =1;
    				$this->view->flag_show = $flag_show;
    				$this->view->thread = $thread;
    				$this->view->user = $user;
    			}
    			
    		}
    		else
    		{
    			echo "Invalid Search";
    		}
    		
    	}
     	catch (Zend_Exception $e) {  
			echo "Error message: " . $e->getMessage() . "\n";  
        
        }
    }


}





